package org.yiming.tools.mqtt.client.client.command;

import lombok.RequiredArgsConstructor;
import org.yiming.tools.mqtt.client.ApplicationContext;
import org.yiming.tools.mqtt.client.client.MqttClient;
import org.yiming.tools.mqtt.client.command.Command;

import java.util.Optional;

/**
 * @author renwenpeng
 * date  2022/3/26 5:50 下午
 */
@RequiredArgsConstructor
public abstract class AbstractMqttCommand implements Command {

    protected final ApplicationContext applicationContext;

    /**
     *
     * args min length
     * @return int
     */
    abstract int argsMinLength();

    /**
     * apply
     * @param mqttClient MqttClient
     * @param args String[]
     * @return String
     */
    abstract String apply(MqttClient mqttClient, String[] args);

    @Override
    public String execute(String[] args) {
        // 校验args
        if (args == null || args.length < argsMinLength()) {
            return "args incorrect";
        }
        // 取命令
        Optional<MqttClient> mqttClientOptional = Optional.ofNullable(MqttCommandContext.getSingleton().getMqttClient());
        if (mqttClientOptional.isPresent()) {
            return apply(mqttClientOptional.get(), args);
        } else {
            // 取第一个
            Optional<MqttClient> firstMqttClientOptional = applicationContext.getMqttClientMap().values().stream().findFirst();
            if (firstMqttClientOptional.isPresent()) {
                MqttCommandContext.getSingleton().setMqttClient(firstMqttClientOptional.get());
                return apply(firstMqttClientOptional.get(), args);
            }
        }
        return "not selected client";
    }
}
